<template>
  <div class="main">
    <el-button
      type="primary"
      :icon="useRenderIcon('ep:plus')"
      @click="openCreateDialog"
      >创建用户</el-button
    >
    <CreateUserDialog ref="createUserRef" @refresh="resetForm(formRef)" />
    <el-form
      ref="formRef"
      :inline="true"
      :model="form"
      class="search-form bg-bg_color w-[99/100] pt-[12px] overflow-auto"
    >
      <el-form-item label="关键字" prop="keyword">
        <el-input
          v-model="form.keyword"
          placeholder="请输入"
          clearable
          class="!w-[180px]"
        />
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          :icon="useRenderIcon('ri:search-line')"
          :loading="loading"
          @click="onSearch"
        >
          搜索
        </el-button>
        <el-button :icon="useRenderIcon(Refresh)" @click="resetForm(formRef)">
          重置
        </el-button>
      </el-form-item>
    </el-form>

    <el-table
      show-overflow-tooltip
      stripe
      border
      :data="tableData"
      style="width: 100%"
    >
      <el-table-column prop="id" label="用户ID" />
      <el-table-column prop="username" label="用户名称" />
      <el-table-column prop="role" label="用户类别" />
      <el-table-column
        prop="status"
        label="用户状态"
        :formatter="val => formatterStatus(val.status)"
        width="100"
      />
      <el-table-column prop="pointsBalance" label="用户积分" />
      <el-table-column
        prop="createTime"
        :formatter="val => handleAutoUTC8(val.createTime)"
        label="创建时间"
        width="220"
      />
      <el-table-column label="操作" fixed="right" width="300">
        <template #default="scope">
          <el-popconfirm
            width="220"
            :icon="InfoFilled"
            icon-color="#626AEF"
            :title="`确定${scope.row.status === 'ENABLED' ? '禁用' : '启用'}该用户吗？`"
            @confirm="confirmStatus(scope.row)"
          >
            <template #reference>
              <el-button
                link
                :type="scope.row.status === 'ENABLED' ? 'danger' : 'success'"
                size="small"
              >
                {{ scope.row.status === "ENABLED" ? "禁用" : "启用" }}
              </el-button>
            </template>
            <template #actions="{ confirm, cancel }">
              <el-button size="small" @click="cancel">取消</el-button>
              <el-button type="danger" size="small" @click="confirm">
                确定
              </el-button>
            </template>
          </el-popconfirm>
          <el-popconfirm
            width="220"
            :icon="InfoFilled"
            icon-color="#626AEF"
            title="确定重置该用户密码吗？"
            @confirm="resetPass(scope.row.id)"
          >
            <template #reference>
              <el-button link type="danger" size="small"> 重置密码 </el-button>
            </template>
            <template #actions="{ confirm, cancel }">
              <el-button size="small" @click="cancel">取消</el-button>
              <el-button type="danger" size="small" @click="confirm">
                确定
              </el-button>
            </template>
          </el-popconfirm>
          <el-button
            link
            type="primary"
            size="small"
            @click="setPoint(scope.row)"
          >
            调整积分
          </el-button>
          <!-- <el-button
            link
            type="success"
            size="small"
            @click="createUserPrice(scope.row)"
          >
            创建用户特定价格
          </el-button> -->
          <el-popconfirm
            width="220"
            :icon="InfoFilled"
            icon-color="#626AEF"
            title="确定设置该用户为代理商吗？"
            @confirm="setAgent(scope.row.id)"
          >
            <template #reference>
              <el-button
                link
                :disabled="scope.row.role !== '普通用户'"
                type="info"
                size="small"
              >
                设为代理商
              </el-button>
            </template>
            <template #actions="{ confirm, cancel }">
              <el-button size="small" @click="cancel">取消</el-button>
              <el-button type="danger" size="small" @click="confirm">
                确定
              </el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      v-model:current-page="pagination.currentPage"
      v-model:page-size="pagination.pageSize"
      :page-sizes="[10, 20, 40, 50]"
      background
      layout="total, sizes, prev, pager, next, jumper"
      :total="pagination.total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
    <el-dialog
      v-model="pointVisible"
      title="调整积分"
      width="500"
      @close="closePoint"
    >
      <div style="padding: 20px 0">
        调整金额(正数增加，负数减少),当前积分：{{ currentPoint || 0 }}
      </div>
      <el-form
        ref="pointFormRef"
        style="width: 100%"
        :model="pointForm"
        :rules="rules"
        label-width="auto"
      >
        <el-form-item label="积分数量" prop="amount">
          <el-input v-model="pointForm.amount" />
        </el-form-item>
        <el-form-item label="调整说明" prop="description">
          <el-input v-model="pointForm.description" type="textarea" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="pointVisible = false">取消</el-button>
          <el-button type="primary" @click="submitPoint(pointFormRef)">
            提交
          </el-button>
        </div>
      </template>
    </el-dialog>
    <CreateUserPriceDialog ref="createUserPriceDialogRef" />
  </div>
</template>

<script lang="ts" setup>
import { handleAutoUTC8 } from "@/utils/tools";
import { InfoFilled } from "@element-plus/icons-vue";
import { reactive, ref, onMounted } from "vue";
import { useRenderIcon } from "@/components/ReIcon/src/hooks";
import Refresh from "@iconify-icons/ep/refresh";
import { message } from "@/utils/message";
import type { FormInstance } from "element-plus";
import {
  getUserList,
  updateUserStatus,
  resetUserPassword
} from "@/api/userApi";
import { setAdminAgents } from "@/api/adminAgentApi";
import { adjustUserPoints } from "@/api/adminPointApi";
import CreateUserDialog from "./components/CreateUserDialog.vue";
import CreateUserPriceDialog from "./components/CreateUserPriceDialog.vue";
import { ElMessageBox } from "element-plus";
import { useClipboard } from "@vueuse/core";

const { copy } = useClipboard();
const createUserRef = ref();
const openCreateDialog = () => {
  createUserRef.value?.open();
};
const formRef = ref();
const pointFormRef = ref<FormInstance>();
const loading = ref(false);
const pointVisible = ref(false);
const currentPoint = ref(0);
const form = reactive({
  keyword: ""
});
const pagination = reactive({
  total: 0,
  pageSize: 10,
  currentPage: 1
});
const pointForm = reactive({
  userId: 0,
  amount: 0,
  description: ""
});
const rules = {
  amount: [
    { required: true, message: "请输入积分调整数量", trigger: "blur" },
    {
      pattern: /^[-+]?(\d+(\.\d+)?|\.\d+)$/,
      message: "请输入正确的数字",
      trigger: "blur"
    }
  ],
  description: [{ required: true, message: "请输入调整说明", trigger: "blur" }]
};
const statusObj = {
  ENABLED: "正常"
};
const formatterStatus = (status: string) => {
  return statusObj[status] ?? "未知";
};
const closePoint = () => {
  pointFormRef.value?.resetFields();
  currentPoint.value = 0;
};
const confirmStatus = async row => {
  try {
    const { id, status } = row;
    await updateUserStatus(id, status === "ENABLED" ? 0 : 1);
    message("操作成功", { type: "success" });
    onSearch();
  } catch (error) {
    console.log(error);
  }
};
const resetPass = async (id: number) => {
  try {
    const { message: text, data } = await resetUserPassword(id);
    const { newPassword } = data;
    message(text || "重置成功", { type: "success" });
    onSearch();
    if (newPassword) {
      await ElMessageBox.confirm(newPassword, "新密码", {
        confirmButtonText: "复制",
        cancelButtonText: "取消",
        type: "success",
        center: true
      });
      copy(newPassword);
    }
  } catch (error) {
    console.log(error);
  }
};

const setAgent = async (id: number) => {
  try {
    const { message: text } = await setAdminAgents(id);
    message(text || "设置成功", { type: "success" });
    onSearch();
  } catch (error) {
    console.log(error);
  }
};

const setPoint = async row => {
  const { id, pointsBalance } = row;
  currentPoint.value = pointsBalance;
  pointForm.userId = id;
  pointVisible.value = true;
};
const createUserPriceDialogRef = ref();
const createUserPrice = (row: any) => {
  createUserPriceDialogRef.value?.open(row);
};
const submitPoint = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      pointForm.amount = +pointForm.amount;
      if (pointForm.amount !== 0) {
        const { userId, amount, description } = pointForm;
        await adjustUserPoints(userId, { amount, description });
        onSearch();
      }
      message("操作成功", { type: "success" });
      pointVisible.value = false;
    } else {
      console.log("error submit!", fields);
    }
  });
};

const tableData = ref([]);

async function onSearch() {
  try {
    loading.value = true;

    const params = {
      page: pagination.currentPage,
      size: pagination.pageSize,
      ...form
    };
    const { data } = await getUserList(params);
    const { records, total, size, current } = data;
    tableData.value = records;
    pagination.total = total;
    pagination.pageSize = size;
    pagination.currentPage = current;
  } catch (error) {
    message("获取数据失败", { type: "error" });
    console.log(error);
  } finally {
    loading.value = false;
  }
}
const handleSizeChange = (val: number) => {
  pagination.currentPage = 1;
  pagination.pageSize = val;
  onSearch();
};
const handleCurrentChange = (val: number) => {
  pagination.currentPage = val;
  onSearch();
};
const resetForm = formEl => {
  if (!formEl) return;
  formEl.resetFields();
  pagination.currentPage = 1;
  onSearch();
};
onMounted(() => {
  onSearch();
});
defineOptions({
  name: "WhatsApp"
});
</script>
<style lang="scss" scoped>
.main {
  padding: 20px;
  background-color: #fff;
  .el-pagination {
    margin-top: 20px;
    justify-content: flex-end;
  }
}
</style>
